<template>
    <Modal v-model="model" :title="title" width="700px">
        <div slot="close"></div>
        <Form ref="form" :model="submitForm" :label-width="100" :rules="rules" label-position="right">
            <Row>
                <FormItem label="壁纸类型" prop="category_ids">
                    <Select v-model="submitForm.category_ids" clearable multiple :default-label="cateGoryDefault">
                        <Option v-for="item in cateGory" :value="item.category_id" :key="item.category_id">{{item.category_name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="壁纸名字" prop="name">
                    <Input type="text" v-model.trim="submitForm.name"/>
                </FormItem>
                <FormItem label="壁纸标题" prop="title">
                    <Input type="text" v-model.trim="submitForm.title"/>
                </FormItem>
                <FormItem label="壁纸排序" prop="sort">
                    <Input type="number" v-model.trim="submitForm.sort"/>
                </FormItem>
                <FormItem label="来源名字" prop="source_name">
                    <Input type="text" v-model.trim="submitForm.source_name"/>
                </FormItem>
                <FormItem label="来源地址" prop="source_path">
                    <Input type="text" v-model.trim="submitForm.source_path"/>
                </FormItem>
                <FormItem label="原图" prop="y_imagePath" v-if="operationType == 'edit'">
                    <Img :src="imagePath" height="100"></Img>
                </FormItem>
                <FormItem label="上传壁纸" prop="images">
                    <Upload
                        :data="submitForm"
                        name="images"
                        type="drag"
                        ref="upload"
                        :format="fileFormt"
                        :headers="headers"
                        :max-size="fileMaxSize"
                        :before-upload="handleBeforeUpload"
                        :on-format-error="handleFormatError"
                        :on-exceeded-size="handleMaxSize"
                        :on-error="handleError"
                        :default-file-list="defaultList"
                        :on-remove="handelRemove"
                        :on-success="handleSuccess"
                        :show-upload-list="false"
                        :action="uploadUrl"
                        >
                        <div v-if="submitForm.set_path == ''" style="padding: 20px 0;">
                            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                            <p>点击或者拖拽上传图片</p>
                        </div>
                        <div v-if="submitForm.set_path != ''" style="padding:10px;">
                            <Row>
                                <Col span="12">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff;padding-top:30px;"></Icon>
                                    <p>点击或者拖拽上传图片</p>
                                </Col>
                                <Col span="12">
                                    <Img :src="imgRootUrl+'/'+submitForm.set_path" height="150"></Img>
                                </Col>
                            </Row>
                        </div>
                    </Upload>
                </FormItem>
                <FormItem label="备注" prop="remark">
                    <Input type="textarea" v-model.trim="submitForm.remark"/>
                </FormItem>
            </Row>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancel">取消</Button>
            <Button type="primary" @click="handleSubmit" :loading="loading">确定</Button>
        </div>
    </Modal>
</template>

<script>
import  Config from '@/config';
import Global from "@/libs/Global.js";
import {getToken} from "@/libs/util.js"
const userInfo = Global.getUserInfo();

export default{
  data: () => {
    return {
      operationType: '',
      title: '',
      uploadUrl: Config.imgUploadUrl,
      imgRootUrl: Config.imgRootUrl,
      imagePath: '',
      cateGoryDefault: [],
      loading: false,
      baseUrl: process.env.NODE_ENV === 'development' ? Config.baseUrl.dev : Config.baseUrl.pro,
      subUrl: '',
      headers: {
        'BzAdminToken': getToken(),
        'BzAdminuserId': userInfo.admin_user_id,
        'BzRedisKey': userInfo.redis_key
      },
      cateGory: [],
      fileMaxSize: 10240,
      fileFormt: ['jpg', 'jpeg', 'png'],
      file: null,
      defaultList: [],
      submitForm: {
        img_id: '',
        category_ids: [],
        name: '',
        title: '',
        sort: 1,
        source_name: '本地上传',
        source_path: 'localhost',
        remark: '',
        y_imagePath: '',
        set_path: ''
      },
      rules: {
        img_id: [{
          required: true,
          message: 'ID不能为空！'
        }],
        set_path: [{
          required: true,
          message: '请先上传图片！'
        }],
        category_ids: [{
          required: true,
          message: '壁纸类型不能为空！'
        }],
        name: [{
          required: true,
          message: '壁纸名称不能为空！'
        }],
        title: [{
          required: true,
          message: '壁纸标题不能为空！'
        }],
        sort: [{
          required: true,
          message: '壁纸排序不能为空！'
        }],
        source_name: [{
          required: true,
          message: '来源名字不能为空！'
        }],
        source_path: [{
          required: true,
          message: '来源地址不能为空！'
        }],
        y_imagePath: [{
          required: true,
          message: '原图地址不能为空！'
        }]
      },
      model: false
    }
  },
  methods: {
    async modelShow (data = [], type = 'add') {
      this.operationType = type
      this.$refs.form.resetFields()
      this.defaultList = []
      // 获取壁纸类别
      let cateGory = await this.post('/admin/CateGory/cateGoryList', {
        get_all: true,
        category_type: 1
      })
      if (cateGory.data.code !== 200) {
        this.$Message.error('获取类别信息异常：' + cateGory.data.msg)
        return
      }
      this.cateGory = cateGory.data.data.list
      if (type == 'add') {
        this.title = '新增壁纸'
        this.subUrl = '/admin/Img/imgAdd'
        this.rules.img_id[0].required = false
        this.rules.y_imagePath[0].required = false
      } else if (type == 'edit') {
        this.title = '编辑壁纸'
        this.subUrl = '/admin/Img/imgEdit'
        let cateGoryIdsList = data.category_ids.split(',')
        let newCateGoryIdList = []
        this.cateGoryDefault = []
        for (let index = 0; index < cateGoryIdsList.length; index++) {
          let id = parseInt(cateGoryIdsList[index])
          newCateGoryIdList.push(id)
          this.cateGoryDefault.push(this.cateGory[id]['category_name'])
        }
        // 显示
        this.submitForm.img_id = data.img_id
        this.submitForm.category_ids = newCateGoryIdList
        this.submitForm.name = data.name
        this.submitForm.title = data.title
        this.submitForm.sort = data.sort
        this.submitForm.source_name = data.source_name
        this.submitForm.source_path = data.source_path
        this.submitForm.remark = data.remark
        this.submitForm.set_path = data.set_path
        this.submitForm.y_imagePath = data.set_path
        this.rules.img_id[0].required = true
        this.rules.y_imagePath[0].required = true
        this.imagePath = Config.imgRootUrl + '/' + data.set_path
      }
      this.model = true
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者 Promise 则停止上传
    handleBeforeUpload (file) {
      this.$Message.loading({ content: '图片上传中', duration: 10 })
      // this.file = file;
      // this.defaultList = [{
      //     name:file.name,
      //     url:file.url
      // }]
      // return false;
    },
    handleFormatError (file) {
      this.$Message.destroy()
      this.$Notice.warning({
        title: '格式错误',
        desc: '文件格式：' + file.name + ' 必须是' + this.fileFormt.join('、')
      })
    },
    handleMaxSize (file) {
      this.$Message.destroy()
      this.$Notice.warning({
        title: '文件过大',
        desc: '文件' + file.name + '过大最大不能超过：' + this.fileMaxSize / 1024 + 'M'
      })
    },
    handleError (error, file, fileList) {
      this.$Message.destroy()
      this.$Notice.error({
        title: '上传失败',
        desc: '文件' + file.name + '上传异常：' + error
      })
    },
    handelRemove (file, fileList) {
      this.file = null
    },
    handleSuccess (res, file) {
      // 上传成功的钩子
      this.$Message.destroy()
      if (res.code === 200) {
        this.submitForm.set_path = res.data.path
        this.$Notice.success({
          title: '图片上传成功',
          desc: res.msg
        })
      } else {
        this.$Notice.error({
          title: '图片上传失败',
          desc: res.msg
        })
      }
    },
    async handleSubmit () {
      this.loading = true
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let resp = await this.post(this.subUrl, this.submitForm)
          const datas = resp.data
          this.loading = false
          if (datas.code == 200) {
            this.$Message.success(this.title + ':' + datas.msg)
            this.$refs.form.resetFields()
            this.$parent.query()
            this.cancel()
          } else {
            this.$Message.error(this.title + ':' + datas.msg)
          }
        } else {
          this.loading = false
          this.$Message.error('表单验证失败！')
        }
      })
    },
    cancel () {
      // 调用关闭父方法
      this.model = false
      this.$refs.form.resetFields()
    }
  }
}
</script>
